<script setup lang="tsx">
import { ref, onMounted, nextTick, inject, computed, watch, onBeforeUnmount } from 'vue'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage
} from 'element-plus'
import baseMap from '../mount/baseMap.vue'
import { searchDriverApi, searchStoreApi, searchWarehouseCateApi } from '@/api/utils/search'
const currentRow: FormData = inject('currentRow') as FormData
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const formRef = ref<InstanceType<typeof ElForm>>()
const driverList = ref<Array<{ name: string; id: number }>>([])
const carList = ref<Array<{ name: string; id: number }>>([])
const networksList = ref<Array<{ name: string; id: number }>>([])
const currentNetworks = ref([])

const formData = ref({
  id: '',
  no: '',
  name: '',
  deliver_driver_id: '',
  warehouse_id: '',
  store_ids: ''
})

const from = ref({
  name: '',
  is_deliver_line_id: ''
})

const options = ref([
  {
    id: 0,
    name: '未占用'
  },
  {
    id: 1,
    name: '已占用'
  }
])

const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)
const routeList = ref([])
const showSelectList = ref(false)

const rules = {
  name: [{ required: true, message: '请填写路线名称', trigger: 'blur' }],
  warehouse_id: [{ required: true, message: '请选择选择起点', trigger: 'blur' }],
  deliver_driver_id: [{ required: true, message: '请选择承运司机', trigger: 'blur' }]
}

onMounted(() => {
  getDriver()
  getStore()
  getWarehouse()
  routeList.value = []
})

// 路线
const baseLineList = computed(() => {
  return [...currentNetworks.value]
})

// 司机
const getDriver = async () => {
  const res = await searchDriverApi({ field: 'id,name' })
  driverList.value = res.data.list
}
// 门店
const getStore = async () => {
  const res = await searchStoreApi({
    page: currentPage.value,
    limit: pageSize.value,
    name: from.value.name,
    is_deliver_line_id: from.value.is_deliver_line_id,
    field: 'id,name,salesman_id,deliver_line_id,long,lat'
  })
  networksList.value = res.data.list.map((val) => {
    return {
      ...val,
      disabled: val.deliver_line_id > 0,
      selected: false
    }
  })
  if (routeList.value.length > 0) {
    networksList.value.forEach((item1) => {
      const found = routeList.value.find((item2) => item1.id === item2.id)
      if (found) {
        item1.selected = true
      }
    })
  }
  setInitialSelection()
  total.value = res.data.count
}
// 网点被选中
const setInitialSelection = () => {
  nextTick(() => {
    networksList.value.forEach((row, index) => {
      if (row.selected) {
        multipleTableRef.value!.toggleRowSelection(networksList.value[index], true)
      }
    })
  })
}
// 仓库
const getWarehouse = async () => {
  const res = await searchWarehouseCateApi({ field: 'id,name,long,lat' })
  carList.value = res.data.list
}
// 添加门店
const showSelect = () => {
  showSelectList.value = true
}
// 门店关闭
const close = () => {
  showSelectList.value = false
}
// 选择网点
const addNetworks = (v) => {
  if (Object.keys(newLat.value).length === 0) {
    ElMessage('请选择起始点！')
    showSelectList.value = false
    multipleTableRef.value!.clearSelection()
    return
  } else {
    currentNetworks.value = [...v]
  }
}
const tableSelect = (rows, row) => {
  let selected = rows.length && rows.indexOf(row) !== -1 // true就是选中，0或者false是取消选中
  if (selected == true) {
    const item = networksList.value.find((item) => item.id === row.id)
    if (item) {
      item.selected = true
      routeList.value.push(row)
    }
  } else {
    const index = routeList.value.findIndex((item) => item.id === row.id)
    if (index !== -1) {
      routeList.value.splice(index, 1)
    }
  }
}
// 过滤网点是否已被使用
const selectable = (row) => {
  return Number(row.deliver_line_id) === 0
}
const newLat = ref({})
const getChange = (val) => {
  var obj = {}
  obj = carList.value.find((i) => {
    return i.id === val
  })
  newLat.value = { long: obj.long, lat: obj.lat, name: obj.name }
}
// 网点搜索重置
const ResetData = () => {
  from.value = {
    name: '',
    is_deliver_line_id: ''
  }
  getStore()
}
// 分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getStore()
}
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getStore()
}

const submit = async () => {
  const valid = await formRef.value?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formDataList = {
      id: formData.value.id,
      no: formData.value.no,
      name: formData.value.name,
      deliver_driver_id: formData.value.deliver_driver_id,
      warehouse_id: formData.value.warehouse_id,
      store_ids: currentNetworks.value.map((item) => item.id).join(',')
    }
    return formDataList
  }
}
watch(
  () => currentRow,
  (row) => {
    if (!row) return
  },
  {
    deep: true,
    immediate: true
  }
)

const reset = () => {
  formData.value = {
    id: '',
    no: '',
    name: '',
    deliver_driver_id: '',
    warehouse_id: '',
    store_ids: ''
  }
}
onBeforeUnmount(reset)
defineExpose({
  submit,
  reset
})
</script>

<template>
  <div class="map_content">
    <base-map :value="baseLineList" :newLat="newLat" />
    <el-form
      class="form_wrap"
      ref="formRef"
      :model="formData"
      :rules="rules"
      :show-message="true"
      status-icon
    >
      <div class="formtable">
        <span class="title">基本信息</span>
        <el-form-item prop="no">
          <div class="form_item_wrap">
            <div class="label">路线编号</div>
            <div class="input">
              <el-input
                style="width: 291px"
                v-model="formData.no"
                disabled
                placeholder="系统自动分配路线编号"
              />
            </div>
          </div>
          <template #error="error">
            <span class="error">{{ error.error }}</span>
          </template>
        </el-form-item>
        <el-form-item prop="name">
          <div class="form_item_wrap">
            <div class="label">路线名称</div>
            <div class="input">
              <el-input style="width: 291px" v-model="formData.name" placeholder="请输入路线名称" />
            </div>
          </div>
          <template #error="error">
            <span class="error">{{ error.error }}</span>
          </template>
        </el-form-item>
        <el-form-item prop="deliver_driver_id">
          <div class="form_item_wrap">
            <div class="label">承运司机</div>
            <div class="input">
              <el-select
                v-model="formData.deliver_driver_id"
                placeholder="请选择承运司机"
                style="width: 291px"
              >
                <el-option
                  v-for="item in driverList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
          </div>
          <template #error="error">
            <span class="error">{{ error.error }}</span>
          </template>
        </el-form-item>
        <el-form-item prop="warehouse_id">
          <div class="form_item_wrap" style="padding-bottom: 20px">
            <div class="label" style="border-bottom-width: 1px">选择起点</div>
            <div class="input" style="border-bottom-width: 1px">
              <el-select
                v-model="formData.warehouse_id"
                placeholder="请选择选择起点"
                style="width: 291px"
                @change="getChange"
              >
                <el-option
                  v-for="item in carList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
          </div>
          <template #error="error">
            <span class="error">{{ error.error }}</span>
          </template>
        </el-form-item>
        <div style="display: flex; justify-content: space-between">
          <span class="title">网点信息</span>
          <el-button @click="showSelect()" type="text"> 添加网点 </el-button>
        </div>
        <el-table
          :data="routeList"
          border
          height="200"
          :header-cell-style="{ background: '#f8f8f9', color: '#515A6e', height: '30px' }"
          :row-style="{ height: '30px' }"
          :cell-style="{ padding: '0px' }"
          style="width: 100%"
        >
          <el-table-column type="index" align="center" />
          <el-table-column align="center" prop="name" label="名称" width="auto" />
        </el-table>
      </div>
    </el-form>
    <div class="networks_wrap" v-show="showSelectList">
      <div style="display: flex; justify-content: space-between">
        <span class="title">添加/修改网点</span>
        <span style="float: right" @click="close()">关闭</span>
      </div>
      <div style="display: inline-block; font-size: 12px; margin: 10px 0px">
        <span>门店：</span>
        <el-input v-model="from.name" size="small" style="width: 100px" placeholder="请输入" />
      </div>
      <div style="display: inline-block; font-size: 12px; margin-left: 10px">
        <span>状态：</span>
        <el-select
          v-model="from.is_deliver_line_id"
          size="small"
          placeholder="请选择"
          style="width: 100px"
        >
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <div style="display: inline-block; margin-left: 10px">
        <el-button type="primary" size="small" @click="getStore()">搜索</el-button>
      </div>
      <div style="display: inline-block; margin-left: 10px">
        <el-button type="info" size="small" @click="ResetData">重置</el-button>
      </div>
      <div style="height: auto">
        <el-table
          ref="multipleTableRef"
          :data="networksList"
          height="350"
          border
          :header-cell-style="{ background: '#f8f8f9', color: '#515A6e', height: '30px' }"
          :row-style="{ height: '30px' }"
          :cell-style="{ padding: '0px' }"
          @selection-change="addNetworks"
          @select="tableSelect"
          style="width: 100%"
        >
          <el-table-column :selectable="selectable" type="selection" width="55" />
          <el-table-column prop="name" label="网点" align="center" width="auto" />
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          style="margin-top: 20px"
        />
      </div>
    </div>
  </div>
</template>
<style scoped lang="less">
.map_content {
  width: 100%;
  height: calc(100vh - 50px - 34px);
  max-height: calc(100vh - 50px - 34px);
  box-sizing: border-box;
  position: relative;

  .networks_wrap,
  .form_wrap {
    position: absolute;
    top: 4px;
    z-index: 2000;
    width: 450px;
    height: calc(100vh - 90px - 34px);
    max-height: calc(100vh - 90px - 34px);
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
  }
  .networks_wrap {
    right: calc(20px + 450px);
    .title {
      line-height: 2.5;
    }
  }
  .form_wrap {
    right: 10px;
    .formtable {
      width: 100%;
      height: 95%;
      overflow-y: auto;
      overflow-x: hidden;
      .title {
        line-height: 2.5;
      }
      .form_item_wrap {
        display: flex;
        .label {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 100px;
          flex-shrink: 0;
          white-space: nowrap;
          border: 1px solid #8f8f8f;
          border-bottom-width: 0;
          user-select: none;
          background: #f2f2f2;
        }
        .input {
          flex: auto;
          border: 1px solid #8f8f8f;
          border-left-width: 0;
          border-bottom-width: 0;
        }

        .tip {
          border: 0;
          justify-content: start;
          font-size: 13px;
          color: #797979;
        }
      }
      .error {
        display: inline-block;
        width: 391px;
        border: 1px solid #8f8f8f;
        border-top: 0;
        transition: all ease-in-out 0.1s;
        color: #f00;
        background-color: rgba(255, 0, 0, 0.1);
      }
    }
    .submit_wrap {
      position: absolute;
      bottom: 20px;
      .btn {
        width: 100px;
        height: 36px;
        color: #fcfcfd;
      }
      .submit {
        background: #008ee0;
        border-color: #008ee0;
      }
      .close {
        background: #797979;
        border-color: #797979;
      }
    }
    & ::v-deep .el-form-item {
      margin: 0;
    }
    & ::v-deep .el-input__inner {
      border: none !important;
    }
  }
}
</style>
